package com.imvc.util;

import com.imvc.exception.DbSessionException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库会话
 *
 * @author ml
 * @create 2017-10-18--16:01
 */
public class DbSession {
    private Connection con=null;
    private PreparedStatement stmt=null;
    private ResultSet rs = null;

    /**
     * 开启数据库会话
     */
    public void open(){
        if(con==null){
            try {
                con=DbResourceManager.getConnection();
            } catch (Exception e) {
                throw new DbSessionException("创建会话失败",e);
            }
        }
    }

    /**
     * 获取数据库绑定的连接
     * @return
     */
    public Connection getConnection() {
        return con;
    }

    /**
     * 关闭数据库会话
     */
    public void close(){
        try {
            DbResourceManager.close(rs);
            DbResourceManager.close(stmt);
            DbResourceManager.close(con);
        }catch (SQLException e){
            throw new DbSessionException("关闭会话失败",e);
        }
    }

    /**
     * 手动开启事务
     */
    public void beginTx(){
        try {
            if(con!=null && !con.isClosed()){
                con.setAutoCommit(false);
            }
        } catch (SQLException e) {
            throw new DbSessionException("开启事务失败",e);
        }
    }

    /**
     * 提交事务
     */
    public void commitTx(){
        try {
            if(con!=null && !con.isClosed()){

                con.commit();
            }
        } catch (SQLException e) {
            throw new DbSessionException("提交事务失败",e);
        }
    }

    /**
     * 回滚事务
     */
    public void rollbackTx(){
        try {
            if(con!=null && !con.isClosed()){
                con.rollback();
            }
        } catch (SQLException e) {
            throw new DbSessionException("回滚事务失败",e);
        }
    }

    /**
     * 执行查询语句
     * @param sql SQL语句
     * @param params 替换sql语句中的占位符的参数
     * @return 结果集
     */
    public ResultSet excuteQuery(String sql,Object...params){
        try{
            stmt=con.prepareStatement(sql);
            for(int i=0;i<params.length;i++){
                stmt.setObject(i+1,params[i]);
            }
            rs=stmt.executeQuery();
        } catch (SQLException e) {
            throw new DbSessionException(e);
        }
        return rs;
    }
}
